import axios from "axios";
import { Message } from "element-ui";
import router from '@/router'

//请求拦截器
axios.interceptors.request.use(config => {
    const tokenStr = window.sessionStorage.getItem('tokenStr')
    if (tokenStr) {
        //请求头中加入token
        config.headers['Authorization'] = tokenStr
    }
    return config
}, error => {
    console.log(error);

})

//响应拦截器
axios.interceptors.response.use(response => {

    //如果返回状态码不是200，如204，206等，则无返回数据
    if (response.status != 200) {
        return;
    }

    //如分页未使用统一实体返回,直接返回数据
    if (response.data.code == null) {
        return response.data
    }

    let message = response.data.msg;

    if (response.data.code != 1) {
        if (message) {
            Message.error(message)
        }
        //错误状态，无返回数据
        return
    }

    if (message) {
        Message.success(message)
    }

    //如果无返回数据，则返回成功状态标记ok
    if (response.data.data == null) {
        return "ok"
    }

    //正常状态，返回数据
    return response.data.data


}, error => {
    //获取状态码
    const status = error.response.status

    switch (status) {
        case 404:
        case 405:
            Message.error('服务器异常')
            break
        case 401:
            Message.error('尚未登陆，请登录')
            router.replace('/')
            break
        case 403:
            Message.error('权限不足，请联系管理员')
            break
        default:
            Message.error('未知错误')
    }
})

let base = ''
export const getRequest = url => {
    return axios.get(`${base}${url}`)
}
export const postRequest = (url, params) => {
    return axios.post(`${base}${url}`, params)
}
export const putRequest = (url, params) => {
    return axios.put(`${base}${url}`, params)
}
export const deleteRequest = url => {
    return axios.delete(`${base}${url}`)
}